package cn.it.shop.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import cn.it.shop.model.Audience;
import cn.it.shop.service.AudienceService;
import cn.it.shop.util.GlobalConstants;
import cn.it.shop.util.HttpUtils;
import cn.it.shop.util.JsonUtil;

/***
 * 微信粉丝service实现
 * @author fangyangsheng
 *
 */
@Service("audienceService")
public class AudienceServiceImpl extends BaseServiceImpl<Audience> implements AudienceService{

	//获取所有用户openid列表
	@Override
	public List<Object> queryOpenidList() {
		List<Object> list = new ArrayList<Object>();//准备存储所有用户openid列表
		
		//从全局变量工具类中取出access_token
		String accessToken = GlobalConstants.getInterfaceUrl("access_token");
		//请求参数
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		//从全局变量工具类中取出获取所有用户openid的url
		String getUserList = GlobalConstants.getInterfaceUrl("getUserList");
		try {
			//请求结果json字符串
			String resultJson = HttpUtils.sendGet(
					getUserList,params);
			if(resultJson != null && !resultJson.equals("")){
				//解析json字符串,获取用户列表map
				Map<String, Object> map = JsonUtil.analyzeJsonMap(resultJson);
				System.out.println(" 返回结果  " + resultJson);
				//解析data
				Map<String, Object> dataMap = JsonUtil.analyzeJsonMap(map.get("data").toString());
				//取出粉丝openid json数组
				list = JsonUtil.analyzeJsonList(dataMap.get("openid").toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("请求所有用户openid异常");
		}
		return list;
	}
	
	//获取所有用户详情的集合
	@Override
	public List<Audience> queryAudienceList() {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * 获取单个用户的详情
	 */
	@Override
	public Audience getAudience(String openId) {
		Audience audience = new Audience();//存放返回值
		
		//从全局变量工具类中取出access_token
		String accessToken = GlobalConstants.getInterfaceUrl("access_token");
		//请求参数
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		params.put("openid",openId);
		params.put("lang", "zh_CN");
		//从全局变量工具类中取出获取所有用户openid的url
		String getUserList = GlobalConstants.getInterfaceUrl("OpenidUserinfoUrl");
		try {
			//请求结果json字符串
			String resultJson = HttpUtils.sendGet(
					getUserList,params);
			if(resultJson != null && !resultJson.equals("")){
				//json字符串转为对应的实体类
				audience = JsonUtil.analyzeJsonBean(resultJson, Audience.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return audience;
	}
	
	/***
	 * 查询用户是否存在数据库,没有则返回true
	 */
	@Override
	public boolean isEmptyAudience(String openId) {
		//查询是否有
		Audience t = (Audience)getSession().get(Audience.class,openId);
		if(t == null){
			return true;
		}
		return false;
	}
	
	

}
